import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Table, Icon, Popover, Checkbox, Button, Modal, Row, Col, Input, Select, Spin } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;

import addressService from 'components/template/select-address-modal/select-address.service'
import 'styles/components/template/select-address-modal/select-address-modal.scss'

class SelectAddressModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      btnLoading: false,
      editAddress: false,
      cityFetching: false,
      areaFetching: false,
      columns: [
        {title: messages('components.key582')/*姓名*/, dataIndex: 'fullName', width: '15%', render: value => (
          <Popover content={value}>{value}</Popover>
        )},
        {title: messages('components.key786')/*详细地址*/, dataIndex: 'fullReceiverAddress', render: value => (
          <Popover content={value}>{value}</Popover>
        )},
        {title: messages('components.key422')/*手机号*/, dataIndex: 'phone', width: '15%'},
        {title: messages('components.key787')/*邮编*/, dataIndex: 'zipCode', width: '10%'},
        {title: messages('common.operation')/*操作*/, dataIndex: 'billingContactOID', width: '10%', render: (value, record) => (
          <a onClick={() => this.handleEditAddress(record)}>{messages('common.update')/*修改*/}</a>
        )}
      ],
      addressData: [],
      provinces:[],
      cities:[],
      areas: [],
      selectedRowKeys: [],
      page: 0,
      size: 5,
      pagination: {
        total: 0
      },
      selectedInfo: null,
      editAddressInfo: {},
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      selectedRowKeys: [nextProps.selectedOID],
    }, () => {
      this.getList();
    });
    if (nextProps.visible && !this.state.provinces.length) {
      this.getList();
      this.getAllProvinces()
    }
  }

  //获取收货地址
  getList = () => {
    const { page, size, selectedRowKeys } = this.state;
    let params = { page, size };
    this.setState({ loading: true });
    addressService.getAddresses(this.props.company.companyOID, params).then(res => {
      res.data.map(item => {
        if(item.billingContactOID === selectedRowKeys[0]){
          this.setState({
            selectedInfo: item,
          })
        }
      });
      this.setState({
        loading: false,
        addressData: res.data,
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({ page: page - 1 }, () => {
        this.getList(false)
      })
  };

  //获取所有省份
  getAllProvinces = () => {
    addressService.getAllProvinces().then(res => {
      this.setState({ provinces: res.data })
    })
  };

  //获取城市
  getCities = (code) => {
    this.setState({ cityFetching: true });
    addressService.getCities(code).then(res => {
      this.setState({
        cities: res.data,
        cityFetching: false
      })
    })
  };

  //获取区域
  getAreas(params){
    this.setState({ areaFetching: true });
    addressService.getAreas(params).then(res => {
      this.setState({
        areas: res.data,
        areaFetching: false
      })
    })
  }

  //选择省份
  handleProvinceChange = (value) => {
    this.props.form.setFieldsValue({ cityRegion:'', area:'' });
    let provinceName = this.state.provinces.filter(item => item.code === value)[0].name;
    this.setState({
      provinceCode: provinceName,
      cities: [],
      areas: []
    },() => {
      this.getCities(value)
    })
  };

  //选择城市
  handleCityChange = (value) => {
    this.props.form.setFieldsValue({ area: '' });
    const { cities, provinceCode } = this.state;
    let CityName = cities.filter(item =>item.code ===value)[0].name;
    this.setState({ cityCode:CityName },() => {
      let params = {};
      params.provinceName = provinceCode;
      params.cityName = cities.filter(item => item.code ===value)[0].name;
      this.getAreas(params)
    })
  };

  //选择区域
  handleAreaChange = () => {};

  //操作 - 修改
  handleEditAddress = (record) => {
    let province = this.state.provinces.filter(item => item.name === record.stateProvince)[0];
    province && this.getCities(province.code);
    this.getAreas({provinceName: record.stateProvince, cityName: record.cityRegion});
    this.setState({
      editAddress: true,
      editAddressInfo: record
    })
  };

  //取消
  onCancel = () => {
    if (this.state.editAddress) {
      Modal.confirm({
        title: messages('components.key788')/*确定放弃编辑中的地址吗*/,
        onOk: () => {
          this.setState({ editAddress: false });
          this.props.onCancel()
        },
      })
    } else {
      this.props.onCancel()
    }
  };

  //确定
  onOk = () => {
    const {editAddress, selectedInfo, selectedRowKeys} = this.state;
    if (editAddress) {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          const { editAddressInfo, provinces, cities, areas } = this.state;
          editAddressInfo.billingContactOID && (values.billingContactOID = editAddressInfo.billingContactOID);
          values.stateProvince = (provinces.filter(item => item.code === values.stateProvince)[0] || {}).name || values.stateProvince;
          values.cityRegion = (cities.filter(item => item.code === values.cityRegion)[0] || {}).name || values.cityRegion;
          values.area = (areas.filter(item => item.code === values.area)[0] || {}).name || values.area;
          values.fullReceiverAddress = `${values.country}${values.stateProvince}${values.cityRegion}${values.area}${values.streetLine}`;
          this.setState({ btnLoading: true });
          addressService.editAddress(!editAddressInfo.billingContactOID, values).then((res) => {
            if(selectedRowKeys[0]){
              if(selectedRowKeys[0] === values.billingContactOID){
                let item = Object.assign(selectedInfo, values);
                this.props.onOk(item);
              }else{
                this.props.onOk(selectedInfo || {});
              }
            }else{
              values.billingContactOID = res.data.billingContactOID;
              this.props.onOk(values);
            }
            this.setState({ editAddress: false, btnLoading: false })
          });
          this.props.onCancel();
        }
      })
    } else {
      this.props.onOk(selectedInfo || {});
      this.props.onCancel();
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, btnLoading, editAddress, cityFetching, areaFetching, columns, addressData, provinces, cities, areas, selectedRowKeys,
      pagination, editAddressInfo, selectedInfo} = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 10, offset: 1}
    };
    const rowSelection = {
      type: 'radio',
      selectedRowKeys,
      onChange: selectedRowKeys => this.setState({selectedRowKeys}),
      onSelect: record => this.setState({selectedInfo: record})
    };
    return (
      <div>
        <div className="select-address-modal"/>
        <Modal visible={this.props.visible}
               width={800}
               title={messages('components.key789')/*选择地址*/}
               getContainer={() => document.getElementsByClassName('select-address-modal')[0]}
               onCancel={this.onCancel}
               onOk={this.onOk}
        >
          <Table rowKey='billingContactOID'
                 loading={loading}
                 dataSource={addressData}
                 columns={columns}
                 rowSelection={rowSelection}
                 pagination={pagination}
                 bordered
                 size='middle'
          />
          <Button type='primary'
                  style={{marginTop: 20}}
                  onClick={() => this.setState({editAddress: true, editAddressInfo: {}, cities: [], areas: []})}>
            <Icon type="plus-circle-o" />{messages('components.key790')/*新增地址*/}
          </Button>
          {editAddress && (
            <Form>
              <Row gutter={30} type="flex" align="top">
                <Col span={6}>
                  <div style={{position:'relative'}}>
                    <FormItem label={messages('components.key791')/*所在地区*/}>
                      {getFieldDecorator("country", {
                        initialValue: editAddressInfo.country || "中国"
                      })(
                        <Input disabled/>
                      )}
                    </FormItem>
                  </div>
                </Col>
                <Col span={6}>
                  <div id='selectProvince' style={{position:'relative'}}>
                    <FormItem label={messages('components.key792')/*请选择省份*/}>
                      {getFieldDecorator("stateProvince", {
                        rules:[{
                          required: true,
                          message: messages('components.key792')/*请选择省份*/
                        }],
                        initialValue: editAddressInfo.stateProvince
                      })(
                        <Select placeholder={messages('components.key792')/*请选择省份*/}
                                getPopupContainer={() => document.getElementById('selectProvince')}
                                onChange={this.handleProvinceChange}>
                          {provinces.map(item => <Option key={item.code}>{item.name}</Option>)}
                        </Select>
                      )}
                    </FormItem>
                  </div>
                </Col>
                <Col span={6}>
                  <div id='selectCity' style={{position:'relative'}}>
                    <FormItem label={messages('components.key793')/*请选择城市*/}>
                      {getFieldDecorator("cityRegion",{
                        rules:[{
                          required: true,
                          message: messages('components.key793')/*请选择城市*/
                        }],
                        initialValue: editAddressInfo.cityRegion
                      })(
                        <Select placeholder={messages('components.key793')/*请选择城市*/}
                                getPopupContainer={()=>document.getElementById('selectCity')}
                                notFoundContent={cityFetching ? <Spin size="small" /> : messages('components.key410')/*无匹配结果*/}
                                onChange={this.handleCityChange}
                        >
                          {cities.map(item => <Option key={item.code}>{item.name}</Option>)}
                        </Select>
                      )}
                    </FormItem>
                  </div>
                </Col>
                <Col span={6}>
                  <div id='selectArea' style={{position:'relative'}}>
                    <FormItem label={messages('components.key794')/*请选择区域*/}>
                      {getFieldDecorator("area",{
                        rules:[{
                          required: false,
                          message: messages('components.key794')/*请选择区域*/
                        }],
                        initialValue: editAddressInfo.area
                      })(
                        <Select placeholder={messages('components.key794')/*请选择区域*/}
                                getPopupContainer={() => document.getElementById('selectArea')}
                                notFoundContent={areaFetching ? <Spin size="small" /> : messages('components.key410')/*无匹配结果*/}
                                onChange={this.handleAreaChange}
                        >
                          {areas.map(item => <Option key={item.code}>{item.name}</Option>)}
                        </Select>
                      )}
                    </FormItem>
                  </div>
                </Col>
              </Row>
              <FormItem {...formItemLayout} label={messages('components.key795')/*详细住所*/}>
                {getFieldDecorator("streetLine",{
                  rules:[{
                    required: true,
                    message: messages('components.key796')/*请输入详细地址*/
                  }],
                  initialValue: editAddressInfo.streetLine
                })(
                  <Input placeholder={messages('components.key796')/*请输入详细地址*/}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('components.key797')/*邮政编码*/}>
                {getFieldDecorator("zipCode",{
                  rules:[{
                    required: true,
                    message: messages('components.key798')/*请输入邮政编码*/
                  },{
                    pattern: /^[0-9][0-9]{5}$/,
                    message: messages('components.key799')/*请输入正确的邮政编码*/
                  }],
                  initialValue: editAddressInfo.zipCode
                })(
                  <Input placeholder={messages('components.key798')/*请输入邮政编码*/}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('components.key800')/*收货人姓名*/}>
                {getFieldDecorator("fullName",{
                  rules:[{
                    required: true,
                    message: messages('components.key801')/*请输入收货人姓名*/
                  }],
                  initialValue: editAddressInfo.fullName
                })(
                  <Input placeholder={messages('components.key801')/*请输入收货人姓名*/} />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('components.key802')/*手机号码*/}>
                {getFieldDecorator("phone", {
                  rules:[{
                    required: true,
                    message: messages('components.key803')/*请输入手机号码*/
                  }, {
                    pattern: "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$",
                    message: messages('components.key804')/*请输入正确的手机号码*/
                  }],
                  initialValue: editAddressInfo.phone
                })(
                  <Input placeholder={messages('components.key803')/*请输入手机号码*/}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label=" " colon={false}>
                {getFieldDecorator("isDefault", {
                  valuePropName: 'checked',
                  initialValue: editAddressInfo.isDefault
                })(
                  <Checkbox>{messages('components.key805')/*设为默认*/}</Checkbox>
                )}
              </FormItem>
            </Form>
          )}
        </Modal>
      </div>
    )
  }
}

SelectAddressModal.propTypes = {
  visible: React.PropTypes.bool.isRequired,
  selectedOID: React.PropTypes.string, //已选择的地址id
  onCancel: React.PropTypes.func,
  onOk: React.PropTypes.func,
};

SelectAddressModal.defaultProps={
  onCancel: () => {},
  onOk: () => {},
};

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

const WrappedSelectAddressModal = Form.create()(SelectAddressModal);

export default connect(mapStateToProps)(WrappedSelectAddressModal)
